﻿/*
 *  Source code courtesy of the desktopWeb.CodePlex.com community project. See MS-PL license on Codeplex.com. 
 *  This is beta code not intended for a production application.
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyData.ExpressionBuilder;
using MyData.ExpressionBuilder.Interfaces;
using System.Collections.ObjectModel;
using MyData.ExpressionBuilder.Model;
using System.Activities.Presentation.Model;
using System.Diagnostics;
using Microsoft.VisualBasic.Activities;
using System.Activities;

namespace MyData.Extensions
{
  public partial class SampleExpressionForm : Form
  {
    Action<object> _onUpdated;
    IExpressionBuilder _eb;
    private ObservableCollection<ListItem> _result = new ObservableCollection<ListItem>();

    public SampleExpressionForm(IEnumerable<ListItem> metadata, IExpressionBuilder eb, Action<object> onUpdated)
    {     
      System.Windows.Forms.Application.EnableVisualStyles();

      InitializeComponent();

      List<ListItem> items = null;
      ModelItem mi = null;
      _onUpdated = onUpdated;
      _eb = eb;

      if (metadata != null)
      {
        //NEXT: Replace with ModelItemExpression
        mi = (from m in metadata where m.Name == "ModelItem" select m.Value).First() as ModelItem;
        string path = (from m in metadata where m.Name == "Path" select m.Value).First() as string;
        List<string> variableNames = (from m in metadata where m.Name == "VariableNames" select m.Value).First() as List<string>;

        this.nameValueExpressionControl.variablesComboBox.ItemsSource = variableNames;

        this.Text += " for " + path;
      }

      if (_eb.ItemsProvider != null)
      {
        _eb.ItemsProvider.MetaData = metadata;
        items = _eb.ItemsProvider.Items;

        //Match ModelItem Dictionary to ItemsProvider.
        if (_eb.Converter.GetType() == typeof(SharePointExpressionTypeConverter))
        {
          //NEXT: items = this.DictionaryValue(mi.TargetExpression(mi.GetModelPath()).ToString(), items);
        }

        this.nameValueExpressionControl.expressionDataGrid.ItemsSource = items;
      }

      if (_eb.Converter.GetType() == typeof(QuotedValueExpressionTypeConverter))
      {
        //Next: Hard-coded Columns[0] and [1]
        this.nameValueExpressionControl.expressionDataGrid.Columns[0].IsReadOnly = true;
        this.nameValueExpressionControl.expressionDataGrid.Columns[1].Visibility = System.Windows.Visibility.Hidden;
        this.nameValueExpressionControl.expressionDataGrid.ColumnHeaderHeight = 0;
        this.nameValueExpressionControl.expressionDataGrid.CanUserAddRows = false;
      }      
    }

    private List<ListItem> DictionaryValue(string expression, List<ListItem> items)
    {
      //Get expression dictionary to restore list

      //NEXT: Reconcile InArgument<string> argTitle, argBody, ...
      VisualBasicValue<Dictionary<string, object>> value = new VisualBasicValue<Dictionary<string, object>>(expression);
      try
      {
        Dictionary<string, object> dictionaryValue = WorkflowInvoker.Invoke(value);
        foreach (var item in items)
        {
          if (dictionaryValue.ContainsKey(item.Name))
          {
            item.Value = dictionaryValue[item.Name].ToString();
          }
        }
      }
      catch(InvalidExpressionException ex)
      { 
        //Log in production application
      }

      return items;

    }

    private void applyButton_Click(object sender, EventArgs e)
    {
      List<ListItem> nameValues = new List<ListItem>();
      object convertedValue = null;

      //NOTE: In the current version you must select each item to commit to the ModelItem expression
      var itemsSource = this.nameValueExpressionControl.expressionDataGrid.SelectedItems;

      if (itemsSource.Count > 0)
      {
        if (_eb.Converter.GetType() == typeof(QuotedValueExpressionTypeConverter))
        {
          ListItem item = this.nameValueExpressionControl.expressionDataGrid.SelectedItem as ListItem;
          item.Value = item.Name;
          nameValues.Add(item);
        }
        else
        {
          foreach (ListItem item in itemsSource)
          {
            nameValues.Add(new ListItem { Name = item.Name, Value = item.Value });
          }
        }

        if (_eb.Converter != null)
        {
          convertedValue = _eb.Converter.CommitedText(nameValues);
        }
        _onUpdated(convertedValue);
      }

      this.Close();

    }

    public ObservableCollection<ListItem> Result
    {
      get { return this._result; }
    }

    private void cancelButton_Click(object sender, EventArgs e)
    {
      this.Close();
    }
  }
}

